package com.zrj.auth.core.extensions.wechat;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author zhaorujie
 */
public class WechatTokenGranter extends AbstractTokenGranter {

    private final static String GRANT_TYPE = "wechat";
    private final AuthenticationManager authenticationManager;

    public WechatTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, AuthenticationManager authenticationManager) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        String code = parameters.get("code");
        String encryptedData = parameters.get("encryptedData");
        String iv = parameters.get("iv");

        //移除后续无用的参数
        parameters.remove(code);
        parameters.remove(encryptedData);
        parameters.remove(iv);

        //未认证的状态
        Authentication authentication = new WechatAuthenticationToken(code, encryptedData, iv);
        ((AbstractAuthenticationToken) authentication).setDetails(parameters);

        try {
            //认证中
            authentication = this.authenticationManager.authenticate(authentication);
        } catch (Exception e) {
            throw new InvalidGrantException(e.getMessage());
        }
        if (authentication != null && authentication.isAuthenticated()) {
            OAuth2Request oAuth2Request = this.getRequestFactory().createOAuth2Request(client, tokenRequest);
            return new OAuth2Authentication(oAuth2Request, authentication);
        } else {
            //认证失败
            throw new InvalidGrantException("Could not authenticate code: " + code);
        }
    }
}
